<template>
  <div class="app-container" style="height: 100%">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="100px">
      <el-form-item label="物料编码" prop="productNo">
        <el-input
          v-model="queryParams.productNo"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料类型" prop="productType">
        <el-select v-model="queryParams.productType" placeholder="请选择物料类型"  >
          <el-option
            v-for="dict in dict.type.basic_product_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="btnGroup">

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['quality:productQualityItem:edit']"
        >设置抽检比例</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleQualityConfig"
        >物料质检配置</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['quality:productQualityItem:add']"
        >导入</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon"
          size="mini"
          @click="handleUpdateOqcTime"
        >设置出货检质检时间</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdateIsOqc"
        >设置出货检</el-button>
      </el-col> -->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange" :height="calcTableHeight"
              highlight-current-row @current-change="rowSelection" >
      <el-table-column type="selection" width="55" align="center" />
      <af-table-column label="物料编号" align="center" prop="productNo" />
      <af-table-column label="物料名称" align="center" prop="productName" />
      <el-table-column label="物料类型" align="center" prop="productType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.basic_product_type" :value="scope.row.productType"/>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="company" />
      <el-table-column label="抽检比例" align="center" prop="qualityRatio" />
      <el-table-column label="是否配置质检项" align="center" prop="isSetQualityItem" >
        <template slot-scope="scope">
          <dict-tag :options="ynList" :value="scope.row.isSetQualityItem"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否出货检" align="center" prop="isOqc" >
        <template slot-scope="scope">
          <dict-tag :options="ynList" :value="scope.row.isOqc"/>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--   质检项明细 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
      <el-tab-pane label="质检项明细" name="detailList">
        <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
      </el-tab-pane>
    </el-tabs>


    <!-- 修改物料抽检比例对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物料编号" prop="productNo" >
          <el-input v-model="form.productNo" placeholder="请输入物料编号"  :disabled=disabled />
        </el-form-item>
        <el-form-item label="物料名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入物料名称" :disabled=disabled />
        </el-form-item>
        <el-form-item label="抽检比例(%)" prop="qualityRatio">
          <el-input v-model="form.qualityRatio" placeholder="请输入抽检比例">
          <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改物料抽检比例对话框 -->
    <el-dialog title="物料质检配置" :visible.sync="openQualityConfig" width="500px" append-to-body>
      <el-form ref="qualityConfigForm" :model="qualityConfigForm" :rules="configRules" label-width="120px">
        <div style="margin-bottom: 10px">
        <span>质检项为空是否默认合格　　　　</span>
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="qualityConfigForm.whetherPass"></el-checkbox>
        </div>
        <span>是否不入待检仓　　　　</span>
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="qualityConfigForm.whetherWaitStock"></el-checkbox>
        <div>
        <span>超期期限（天）　　　　</span>
          <el-input-number
            prop="overduePeriod"
            :controls="false"
            style="display: inline-block;width: 100px;height: 10px"
            v-model="qualityConfigForm.overduePeriod"></el-input-number>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改是否出货检对话框 -->
    <el-dialog title="设置出货检" :visible.sync="oqcDisabled" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="是否出货检" prop="isOqc">
          <el-select
            v-model="form.isOqc"
            placeholder="是否出货检"
            clearable
            style="width: 240px"
          >
            <el-option key="Y" label="是" value="Y"/>
            <el-option key="N" label="否" value="N"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改出货检质检时间 -->
    <el-dialog :title="title" :visible.sync="openQcTime" width="500px" append-to-body>
      <el-form ref="oqcForm" :model="oqcForm" :rules="oqcRules" label-width="120px">
        <el-form-item label="质检时间" prop="qcTime" >
          <el-input style="width: 240px" v-model="oqcForm.qcTime" placeholder="质检时间" />
        </el-form-item>
        <el-form-item label="质检周期" prop="qcCycle">
          <el-select
            v-model="oqcForm.qcCycle"
            placeholder="质检周期"
            clearable
            style="width: 240px"
          >
            <el-option key="DAY" label="日" value="DAY"/>
            <el-option key="WEEK" label="周" value="WEEK"/>
            <el-option key="MONTH" label="月" value="MONTH"/>
            <el-option key="YEAR" label="年" value="YEAR"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveOqcTime">确 定</el-button>
        <el-button @click="cancelOqc">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixin/pageSearchTable";
import { getProductPage, getProductQualityConfig,setProductQualityConfig } from "./api/productBom";
import { getConfigKey, updateConfig } from "@/api/system/config";
import { listProduct,getProduct,updateProduct} from "@/api/basic/product";
import { getToken } from "@/utils/auth";
import detailPage from "../productQualityItemDetail/index";
import { isEmpty, isQualityFour,isPositiveInt} from '@/utils/validate';

export default {
  name: "productBom",
  dicts: ['basic_product_type'],
  mixins:[mixins],
  components: { detailPage },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      productNos: [],
      selectionRows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据表格数据
      bomList: [],
      // 物料列表
      productList: [],
      ynList: [
        {
          id:0,
          label:'是',
          value:'Y'
        },
        {
          id:1,
          label:'否',
          value:'N'
        }
        ],
      // 物料列表
      bomTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openQualityConfig: false,
      openQcTime: false,
      disabled : false,
      oqcDisabled : false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        searchQualityItem:'Y',
        orderStatus: null,
        customerNo: null,
        customerName: null,
        workOrderNo: null,
        createUser: null,
        updateUser: null,
        sort: null
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/quality/productQualityItem/importData"
      },
      // 表单参数
      form: {},
      qualityConfigForm: {},
      oqcForm: {
        oqcTIme:'',
        oqcCycle:''
      },
      //页面下方明细的选项
      activeTab:'detailList',
      //传递给订单详情的数据
      orderData:{},
      rules: {
        qualityRatio: [
          { required: true, message: "抽检比例不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if ((isEmpty(value) || isQualityFour(value))) {
                if (value <= 100) {
                  callback();
                } else {
                  callback('抽检比例不能大于100');
                }
              } else {
                callback('请输入数字，保留4位小数');
              }

            },
            trigger: "blur",
          },
        ],
        isOqc: [
          { required: true, message: "请选择是否出货检", trigger: "change" },
        ],
      },
      oqcRules: {
        qcTime: [
          { required: true, message: "质检时间不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if ((isEmpty(value) || isQualityFour(value))) {
                callback();
              } else {
                callback('请输入数字，保留4位小数');
              }

            },
            trigger: "blur",
          },
        ],
        qcCycle: [
          { required: true, message: "质检周期不能为空", trigger: "change" },
        ],
      },
      configRules:{
        overduePeriod: [
          {
            validator: (rule, value, callback) => {
              if (typeof value === 'string') {
                callback('请输入正整数')
                return;
              }
              if ((isEmpty(value) || isPositiveInt(value))) {
                callback();
              } else {
                callback('请输入正整数');
              }

            },
            trigger: "blur",
          },
        ],
      }
    };
  },
  created() {
    this.getListCustomer();
    this.getList();
  },
  methods: {
    handleTabClick(value){
    },
    getListCustomer(){
      listProduct({pageNum:1,pageSize:0}).then(response => {
        this.productList = response.rows;
      });
    },
    /** 查询单据列表 */
    getList() {
      this.loading = true;
      this.rowSelection({});
      this.queryParams.searchQualityItem = 'Y';
      getProductPage(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.bomList.forEach((row) => {
          if (row.qualityRatio) {
            row.qualityRatio = row.qualityRatio + '%';
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openQualityConfig = false;
      this.oqcDisabled = false;
      this.reset();
    },
    /** 修改抽检比例操作 */
    handleUpdate(row) {
      this.disabled=true;
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "设置抽检比例";
      });
    },
    /** 修改物料质检配置 */
    handleQualityConfig() {
      // 如果只勾选了一个，查询配置
      if (this.productNos.length === 1){
        getProductQualityConfig(this.productNos[0]).then(response => {
          if (response.data){
            this.$set(this,'qualityConfigForm',{
              whetherPass:response.data.whetherPass?response.data.whetherPass.toString():'',
              whetherWaitStock:response.data.whetherWaitStock?response.data.whetherWaitStock.toString():'',
              overduePeriod:response.data.overduePeriod
            });
          }else {
            this.$set(this,'qualityConfigForm',{whetherPass:'0',whetherWaitStock:'0'});
          }
        });
      }else {
        this.$set(this,'qualityConfigForm',{whetherPass:'0',whetherWaitStock:'0'});
      }

      this.openQualityConfig = true;

    },
    submitConfigForm(){
      this.$refs["qualityConfigForm"].validate(valid => {
        if (valid) {
          if (this.qualityConfigForm.overduePeriod !== undefined && this.qualityConfigForm.overduePeriod !== null && this.qualityConfigForm.overduePeriod <= 0) {
            this.$modal.msgWarning("超期期限请输入大于0的正整数");
            return;
          }
          if (!isPositiveInt(this.qualityConfigForm.overduePeriod)) {
            this.$modal.msgWarning("超期期限请输入大于0的正整数");
            return;
          }
          setProductQualityConfig({
            productNos:this.productNos,
            whetherPass:this.qualityConfigForm.whetherPass,
            whetherWaitStock:this.qualityConfigForm.whetherWaitStock,
            overduePeriod:this.qualityConfigForm.overduePeriod,
          }).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.openQualityConfig = false;
          });
        }
      });

    },
    /** 修改是否出货检操作 */
    handleUpdateIsOqc(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.oqcDisabled = true;
      });
    },
    /** 修改出货检质检时间 */
    handleUpdateOqcTime() {
      this.disabled=true;
      this.reset();
      const key = 'qc.oqcTime'
      getConfigKey(key).then(res => {
        let configStr = res.msg;
        this.$set(this.oqcForm,'qcTime',configStr.split("-")[0]);
        this.$set(this.oqcForm,'qcCycle',configStr.split("-")[1]);
        this.openQcTime = true;
        this.title = "设置出货检质检时间";
      });
    },
    /** 修改出货检质检时间 */
    handleSaveOqcTime() {
      this.$refs["oqcForm"].validate(valid => {
        if (valid) {
          const key = 'qc.oqcTime'
          updateConfig({
            configKey:key,
            configValue:this.oqcForm.qcTime + "-" + this.oqcForm.qcCycle
          }).then(res => {
            this.$modal.msgSuccess("修改成功");
            this.openQcTime = false;
          });
        }
      });

    },
    cancelOqc(){
      this.openQcTime = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,'queryParams',{});
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.nos = selection.map(item => item.no)
      this.productNos = selection.map(item => item.productNo)
      this.single = selection.length!==1
      this.selectionRows = selection
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.oqcDisabled = false;
              this.getList();
            });
          }
        }
      });
    },
    //行选择
    rowSelection(row){
      this.orderData = row;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料质检项导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
        const a = document.createElement('a');
        a.href = `${process.env.BASE_URL}static/file/物料质检项导入模板.xlsx` //'./static/file/物料BOM导入模板.xlsx';
        a.click();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
